package com.daiji.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

public class JDBCUtil {

    /**
     * 创建数据库连接池
     */
    private static DataSource dataSource = null;
    static {
        //读取配置文件
        InputStream ras = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        Properties properties = new Properties();
        try {
            properties.load(ras);
            //创建数据库连接池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从数据库连接池中获取Connection连接
     * @return
     */
    public static Connection on(){
        try {
            //返回一个从数据库连接池中获取的连接
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /**
     * 给sql语句中的变量设置值
     * @param ps
     * @param objects
     */
    public static void setSql(PreparedStatement ps,Object... objects){
        if (objects.length>0){
            for (int i = 0; i < objects.length; i++) {
                try {
                    ps.setObject(i+1,objects[i]);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

    /**
     * 查询数据返回List<Map>集合
     * @param sql
     * @param objects
     * @return
     */
    public static List<Map<String,Object>> queryMap(String sql,Object... objects){

        Connection conn = on();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        List<Map<String,Object>> list = null;
        try {
            ps = conn.prepareStatement(sql);//sql预编译
            setSql(ps,objects);

            resultSet = ps.executeQuery();//获取ps所有的内容
            list = new ArrayList<>();
            while (resultSet.next()){
                Map<String, Object> map = new HashMap<>();
                for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
                    map.put(resultSet.getMetaData().getColumnName(i+1),resultSet.getObject(i+1));
                }
                list.add(map);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            off(resultSet,ps,conn);
        }
        return list;
    }

    /**
     * 查询数据返回List<List>集合
     * @param sql
     * @param objects
     * @return
     */
    public static List<List> queryList(String sql,Object... objects){

        Connection conn = on();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        List<List> list = null;
        try {
            ps = conn.prepareStatement(sql);//sql预编译
            setSql(ps,objects);

            resultSet = ps.executeQuery();//获取ps所有的内容
            list = new ArrayList<>();
            while (resultSet.next()){
                List<Object> list1 = new ArrayList<>();
                for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
                    list1.add(resultSet.getObject(i+1));
                }
                list.add(list1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            off(resultSet,ps,conn);
        }
        return list;
    }

    /**
     * 增删改方法，返回影响的行数
     * @param sql
     * @param objects
     * @return
     */
    public static int update(String sql,Object... objects){
        Connection conn = on();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            setSql(ps,objects);

            int i = ps.executeUpdate();
            return i;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            off(null,ps,conn);
        }
        return -1;
    }

    /**
     * 增删改方法，返回影响的行数
     * @param sql
     * @param objects
     * @return
     */
    public static int insert(String sql,Object... objects){
        Connection conn = on();
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            setSql(ps,objects);
            int i = ps.executeUpdate();

            ResultSet keys = ps.getGeneratedKeys();

            while (keys.next()){
                Object o = keys.getObject(1);
                return Integer.parseInt(o.toString());
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            off(null,ps,conn);
        }
        return -1;
    }

    /**
     * 关闭所有开启的连接
     * @param resultSet
     * @param preparedStatement
     * @param connection
     */
    public static void off(ResultSet resultSet,PreparedStatement preparedStatement,Connection connection){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
}
